package com.sanglh.tutorial.androidtouch;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat.Builder;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.sanglh.tutorial.R;
import com.sanglh.tutorial.common.base.Logging;
import com.sanglh.tutorial.common.util.AppUtils;

public class AndroidTouchService extends Service implements OnClickListener,
		OnLongClickListener {

	private WindowManager mWindowManager;
	private LayoutParams mWholeTouchParams;
	private ImageButton mAndroidTouchView;
	private View mTouchView1;
	private LayoutParams mTouchParams1;
	private View mTouchView2;
	private LayoutParams mTouchParams2;
	private ImageView mHome;
	float downX;
	float downY;
	private Object mSyncObject = new Object();

	public AndroidTouchService() {
	}

	public static void show(Context context) {
		context.startService(new Intent(context, AndroidTouchService.class));
	}

	@Override
	public void onCreate() {
		mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		initIOSTouchView();
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		if (mAndroidTouchView != null) {
			mWindowManager.removeView(mAndroidTouchView);
		}

		super.onDestroy();
	}

	private void initIOSTouchView() {
		int flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
				| LayoutParams.FLAG_SHOW_WHEN_LOCKED
				| LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
				| LayoutParams.FLAG_LAYOUT_IN_SCREEN
				| LayoutParams.FLAG_NOT_FOCUSABLE;
		mWholeTouchParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, 0, 0,
				LayoutParams.TYPE_SYSTEM_ERROR, flags, PixelFormat.TRANSLUCENT);
		mAndroidTouchView = (ImageButton) LayoutInflater.from(
				getApplicationContext()).inflate(
				R.layout.view_android_icon_touch, null);
		mAndroidTouchView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mWindowManager.removeView(mAndroidTouchView);
				mWindowManager.addView(mTouchView1, mTouchParams1);
			}
		});
		mAndroidTouchView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					downX = event.getRawX();
					downY = event.getRawY();
					break;
				case MotionEvent.ACTION_MOVE:
					int deltaX = (int) (event.getRawX() - downX);
					int deltaY = (int) (event.getRawY() - downY);
					downX = event.getRawX();
					downY = event.getRawY();
					mWholeTouchParams.x += deltaX;
					
					mWholeTouchParams.y += deltaY;
					Logging.log(" x = " + mWholeTouchParams.x);
					Logging.log(" y = " + mWholeTouchParams.y);
					mWindowManager.updateViewLayout(mAndroidTouchView,
							mWholeTouchParams);
					break;
				case MotionEvent.ACTION_UP:
					downX = event.getRawX();
					downY = event.getRawY();
					Point point = new Point();
					mWindowManager.getDefaultDisplay().getSize(point);
					int width = point.x;
					int height = point.y;
					if (downX == width || downY == height) {
						break;
					}
					float deltaW = width - downX;
					float deltaH = height - downY;
					int newX = 0;
					int newY = 0;
					if (downX < deltaW) {
						if (downX < downY && downX < deltaH) {
							newX = getNewPosition(mWholeTouchParams.x, width);
						} else {
							newY = getNewPosition(mWholeTouchParams.y, height);
						}
					} else {
						if (deltaW < downY && deltaW < deltaH) {
							newX = getNewPosition(mWholeTouchParams.x, width);
						} else {
							newY = getNewPosition(mWholeTouchParams.y, height);
						}
					}
					animationToNewPosition(newX, newY);
				default:
					break;
				}
				return false;
			}

		});
		mTouchParams1 = new LayoutParams(400, 400, 0, 0,
				LayoutParams.TYPE_SYSTEM_ERROR, flags, PixelFormat.TRANSLUCENT);
		mTouchView1 = LayoutInflater.from(getApplicationContext()).inflate(
				R.layout.view_android_touch1, null);
		mTouchView1.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int action = event.getAction();
				switch (action) {
				case MotionEvent.ACTION_OUTSIDE:
					goBackHome(mTouchView1);
					break;

				default:
					break;
				}
				return false;
			}
		});

		mHome = (ImageView) mTouchView1.findViewById(R.id.img_home);
		mHome.setOnClickListener(this);
		((ImageView) mTouchView1.findViewById(R.id.img_settings))
				.setOnClickListener(this);
		((ImageView) mTouchView1.findViewById(R.id.img_lock))
				.setOnClickListener(this);
		((ImageView) mTouchView1.findViewById(R.id.img_more))
				.setOnClickListener(this);
		// mIOSTouchView.setOnTouchListener(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// // mIOSTouchParams.x = (int) event.getX();
		// // mIOSTouchParams.y = (int) event.getY();
		// // mWindowManager.updateViewLayout(mIOSTouchView, mIOSTouchParams);
		// return true;
		//
		// }
		// });
		mWindowManager.addView(mAndroidTouchView, mWholeTouchParams);

		mTouchParams2 = new LayoutParams(400, LayoutParams.WRAP_CONTENT, 0, 0,
				LayoutParams.TYPE_SYSTEM_ERROR, flags, PixelFormat.TRANSLUCENT);
		mTouchView2 = LayoutInflater.from(getApplicationContext()).inflate(
				R.layout.view_android_touch2, null);
		mTouchView2.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int action = event.getAction();
				switch (action) {
				case MotionEvent.ACTION_OUTSIDE:
					goBackHome(mTouchView2);

					break;

				default:
					break;
				}
				return false;
			}
		});
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO: Return the communication channel to the service.
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		Builder builder = new Builder(this);
		builder.setContentText(getString(R.string.app_name));
		builder.setContentTitle(getString(R.string.app_name));
		builder.setAutoCancel(false);

		builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(
				this, DummyActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0));

		builder.setSmallIcon(R.drawable.ic_android);
		Notification notif = builder.build();

		startForeground(8001, notif);
		return START_STICKY;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_home:
			AppUtils.launchHomeApp(getApplicationContext());
			break;
		case R.id.img_settings:
			AppUtils.launchSettingsApp(getApplicationContext());
			break;
		case R.id.img_lock:
			lock();
			break;
		case R.id.img_more:
			more();
			break;
		default:
			break;
		}
		goBackHome(mTouchView1);

	}

	private void more() {
		mWindowManager.addView(mTouchView2, mTouchParams2);

	}

	private void lock() {
		DevicePolicyManager devicePolicyManager = (DevicePolicyManager) AndroidTouchService.this
				.getSystemService(Context.DEVICE_POLICY_SERVICE);
		ComponentName compName = new ComponentName(getApplicationContext(),
				DeviceReceiver.class);
		if (devicePolicyManager.isAdminActive(compName)) {
			devicePolicyManager.lockNow();

		} else {
			DummyActivity.requestAddDevice(getApplicationContext());
		}
	}

	@Override
	public boolean onLongClick(View v) {
		// TODO Auto-generated method stub
		return false;
	}

	private int getNewPosition(int curDimension, int maxDimension) {
		if (curDimension > 0) {
			return maxDimension / 2;
		} else {
			return -maxDimension / 2;
		}
	}

	private void animationToNewPosition(final int newX, final int newY) {
		synchronized (mSyncObject) {
			if (newX != 0) {
				int curX = mWholeTouchParams.x;
				final int deltaX = (newX - curX) / 20;
				new CountDownTimer(200, 10) {

					@Override
					public void onTick(long millisUntilFinished) {
						try {
							mWholeTouchParams.x += deltaX;
							mWindowManager.updateViewLayout(mAndroidTouchView,
									mWholeTouchParams);
						} catch (Exception e) {
							cancel();
						}

					}

					@Override
					public void onFinish() {
						try {
							mWholeTouchParams.x = newX;
							mWindowManager.updateViewLayout(mAndroidTouchView,
									mWholeTouchParams);
						} catch (Exception e) {
							cancel();
						}
					}

				}.start();
				return;
			}

			if (newY != 0) {
				int curY = mWholeTouchParams.y;
				final int deltaY = (newY - curY) / 20;
				new CountDownTimer(200, 10) {

					@Override
					public void onTick(long millisUntilFinished) {
						try {
							mWholeTouchParams.y += deltaY;
							mWindowManager.updateViewLayout(mAndroidTouchView,
									mWholeTouchParams);
						} catch (Exception e) {
							cancel();
						}

					}

					@Override
					public void onFinish() {
						try {
							mWholeTouchParams.y = newY;
							mWindowManager.updateViewLayout(mAndroidTouchView,
									mWholeTouchParams);
						} catch (Exception e) {
							cancel();
						}

					}
				}.start();
			}

		}

	}
	private void goBackHome(View removeView) {
		try {
			mWindowManager.removeView(removeView);
			mWindowManager.addView(mAndroidTouchView, mWholeTouchParams);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}

}
